/*
 * RecordClearThread.cpp
 *
 *  Created on: 2018年5月17日
 *      Author: zhengboyuan
 */

#include "RecordClearThread.h"
#include "BasicMacro.h"
#include "Path.h"
#include "CLog.h"

RecordClearThread::RecordClearThread(DataStorePtr& dataStore, const char* device, RecordClearSink* sink):
	m_dataStore(dataStore),
	m_device(device),
	m_cleared(),
	m_sink(sink)
{
}

RecordClearThread::~RecordClearThread()
{
}

int RecordClearThread::run()
{
	while (!m_canExit)
	{
		int offset = 0;
		if (!batClear(offset))
		{
			break;
		}
	}

	CLog::info("device(%s) record cleared %d\n", m_device.c_str(), m_cleared);

	if (!m_canExit && m_sink)
	{
		m_sink->onRecordCleared(m_device.c_str(), m_cleared);
	}

	return 0;
}

void RecordClearThread::doStop()
{
	m_event.post();
}

bool RecordClearThread::batClear(int& offset)
{
	av::MRecord records[256];
	memset(&records, 0, sizeof(records));
	int size = ARRAY_SIZE(records);
	size = m_dataStore->listRecord(m_device.c_str(), offset, records, size);
	if (size <= 0)
	{
		return false;
	}

	offset += size;

	for (int i = 0; i < size && !m_canExit; i++)
	{
		const char* filepath = records[i].filepath;
		if (!comn::Path::exist(filepath))
		{
			m_dataStore->removeRecord(records[i].id);
			m_cleared ++;
		}
	}
	return true;
}
